//
//  WQExportVideoCommand.m
//  VideoDemo
//
//  Created by C on 2019/8/20.
//  Copyright © 2019 c. All rights reserved.
//

#import "WQExportVideoCommand.h"

@implementation WQExportVideoCommand

- (void)performWithAsset:(AVAsset *)asset
{
    // Step 1
    // Create an outputURL to which the exported movie will be saved
    NSString *rootVideoDir = [WQVideoFilePath getVideoPathCache];
    self.exporName = [WQVideoFilePath getVideoNameWithType:@"mp4"];
    self.exporPath = [NSString stringWithFormat:@"%@/%@",rootVideoDir,self.exporName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:self.exporPath];
    if (existed != YES) {
        [fileManager createFileAtPath:self.exporPath contents:nil attributes:nil];
    }
    
    NSURL *outputURL = [NSURL fileURLWithPath:self.exporPath];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:[outputURL path] error:nil];
    
    // Step 2
    // Create an export session with the composition
    self.exportSession = [[AVAssetExportSession alloc] initWithAsset:[self.mutableComposition copy] presetName:AVAssetExportPresetMediumQuality];
    
    self.exportSession.videoComposition = self.mutableVideoComposition;
//    self.exportSession.audioMix = self.mutableAudioMix;
    self.exportSession.outputURL = outputURL;
    self.exportSession.outputFileType = AVFileTypeMPEG4;
    self.exportSession.shouldOptimizeForNetworkUse = YES;
    
    [self.exportSession exportAsynchronouslyWithCompletionHandler:^(void){
        switch (self.exportSession.status) {
            case AVAssetExportSessionStatusCompleted:
                
                // Step 3
                // Notify AVSEViewController about export completion
                [[NSNotificationCenter defaultCenter]
                 postNotificationName:AVSEExportCommandCompletionNotification
                 object:self];
                break;
            case AVAssetExportSessionStatusFailed:
                [[NSNotificationCenter defaultCenter]
                 postNotificationName:AVSEExportCommandCompletionNotification
                 object:self];
                NSLog(@"Failed:%@",self.exportSession.error);
                break;
            case AVAssetExportSessionStatusCancelled:
                [[NSNotificationCenter defaultCenter]
                 postNotificationName:AVSEExportCommandCompletionNotification
                 object:self];
                NSLog(@"Canceled:%@",self.exportSession.error);
                break;
            default:
                break;
        }
    }];
}

@end
